package com.drawingtimer.admin.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.drawingtimer.admin.mapper.TProcessInfoMapper;
import com.drawingtimer.admin.model.entity.TProcessInfo;
import com.drawingtimer.admin.model.entity.TTimeSegmentPause;
import com.drawingtimer.admin.model.entity.TTimeSegmentRecord;
import com.drawingtimer.admin.model.vo.TTimeSegmentPausePageVO;
import com.drawingtimer.admin.model.qo.TTimeSegmentPauseQO;
import com.drawingtimer.admin.mapper.TTimeSegmentPauseMapper;
import com.drawingtimer.admin.service.TTimeSegmentPauseService;
import com.drawingtimer.admin.model.qo.TTimeSegmentPauseQO;
import com.hccake.ballcat.common.model.domain.PageParam;
import com.hccake.ballcat.common.model.domain.PageResult;
import com.hccake.extend.mybatis.plus.service.impl.ExtendServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 时间段暂停记录
 *
 * @author ballcat 2025-04-30 14:13:33
 */
@Service
public class TTimeSegmentPauseServiceImpl extends ExtendServiceImpl<TTimeSegmentPauseMapper, TTimeSegmentPause>
		implements TTimeSegmentPauseService {

	@Autowired
	private TTimeSegmentRecordServiceImpl tTimeSegmentRecordService;

	@Autowired
	private TProcessInfoMapper tProcessInfoMapper;

	/**
	 * 根据QueryObeject查询分页数据
	 * @param pageParam 分页参数
	 * @param qo 查询参数对象
	 * @return PageResult<TTimeSegmentPausePageVO> 分页数据
	 */
	@Override
	public PageResult<TTimeSegmentPausePageVO> queryPage(PageParam pageParam, TTimeSegmentPauseQO qo) {
		return baseMapper.queryPage(pageParam, qo);
	}

	@Override
	public boolean getByRecordIdAndEndTimeIsNull(Long recordId) {
		LambdaQueryWrapper<TTimeSegmentPause> wrapper = new LambdaQueryWrapper<>();
		wrapper.eq(TTimeSegmentPause::getRecordId, recordId);
		wrapper.isNull(TTimeSegmentPause::getPauseEnd);
		List<TTimeSegmentPause> list = baseMapper.selectList(wrapper);
		if (!CollectionUtil.isEmpty(list)) {
			return true;
		}
		return false;
	}

	@Override
	@Transactional
	public boolean saveAndUpdateTTimeSegmentRecord(TTimeSegmentPause tTimeSegmentPause) {
		if (tTimeSegmentPause == null || tTimeSegmentPause.getRecordId() == null) {
			throw new IllegalArgumentException("暂停记录或记录ID不能为空");
		}

		LocalDateTime pauseStart = tTimeSegmentPause.getPauseStart();
		if (pauseStart == null) {
			throw new IllegalArgumentException("暂停开始时间不能为空");
		}

		if (!save(tTimeSegmentPause)) {
			return false;
		}

		TTimeSegmentRecord tTimeSegmentRecord = tTimeSegmentRecordService
			.getByRecordId(tTimeSegmentPause.getRecordId());
		if (tTimeSegmentRecord == null) {
			throw new RuntimeException("找不到对应的记录，recordId: " + tTimeSegmentPause.getRecordId());
		}

		List<TTimeSegmentPause> list = baseMapper.selectList(new LambdaQueryWrapper<TTimeSegmentPause>()
			.eq(TTimeSegmentPause::getRecordId, tTimeSegmentPause.getRecordId())
			.orderByDesc(TTimeSegmentPause::getId));

		Long currentTotal = tTimeSegmentRecord.getTotalTimeConsumption();

		if (!CollectionUtil.isEmpty(list)) {
			if (list.size() == 1) {
				LocalDateTime startTime = tTimeSegmentRecord.getStartTime();
				if (startTime != null) {
					long seconds = Math.max(0, Duration.between(startTime, pauseStart).getSeconds());
					tTimeSegmentRecord.setTotalTimeConsumption((currentTotal != null ? currentTotal : 0L) + seconds);
				}
			}
			else if (list.size() > 1) {
				TTimeSegmentPause lastPause = list.get(1);
				LocalDateTime lastPauseEnd = lastPause.getPauseEnd();
				if (lastPauseEnd != null) {
					long seconds = Math.max(0, Duration.between(lastPauseEnd, pauseStart).getSeconds());
					tTimeSegmentRecord.setTotalTimeConsumption((currentTotal != null ? currentTotal : 0L) + seconds);
				}
			}
		}

		if (!tTimeSegmentRecordService.updateById(tTimeSegmentRecord)) {
			throw new RuntimeException("更新总耗时失败，recordId: " + tTimeSegmentPause.getRecordId());
		}

		// 修改工序信息状态
		LambdaUpdateWrapper<TProcessInfo> tProcessInfoUpdateWrapper = new LambdaUpdateWrapper<>();
		tProcessInfoUpdateWrapper.eq(TProcessInfo::getId, tTimeSegmentRecord.getProcessId())
			.eq(TProcessInfo::getFlowCardNumber, tTimeSegmentRecord.getFlowCardNumber())
			.set(TProcessInfo::getStatus, 2);
		tProcessInfoMapper.update(new TProcessInfo(), tProcessInfoUpdateWrapper);

		return true;
	}

	@Override
	public boolean updateResumeTimer(TTimeSegmentPause tTimeSegmentPause) {
		baseMapper.updateById(tTimeSegmentPause);
		TTimeSegmentPause byId = getById(tTimeSegmentPause.getId());
		TTimeSegmentRecord tTimeSegmentRecord = tTimeSegmentRecordService.getByRecordId(byId.getRecordId());
		// 修改工序信息状态
		LambdaUpdateWrapper<TProcessInfo> tProcessInfoUpdateWrapper = new LambdaUpdateWrapper<>();
		tProcessInfoUpdateWrapper.eq(TProcessInfo::getId, tTimeSegmentRecord.getProcessId())
			.eq(TProcessInfo::getFlowCardNumber, tTimeSegmentRecord.getFlowCardNumber())
			.set(TProcessInfo::getStatus, 1);
		tProcessInfoMapper.update(new TProcessInfo(), tProcessInfoUpdateWrapper);
		return true;
	}

}
